package main

import (
	"fmt"
	"google.golang.org/grpc"
	"mock/stream_grpc_test/proto/pb"
	"net"
	"sync"
	"time"
)

var PORT = ":8888"

type Server struct {}

func (s *Server) GetStream(data *proto.StreamReqData, server proto.Greeter_GetStreamServer) error {
	i := 0
	for  {
		i ++
		err := server.Send(&proto.StreamResData{
			Data: fmt.Sprintf("%v", time.Now().Unix()),
		})
		if err != nil {
			return err
		}
		time.Sleep(time.Second)
		if i > 10 {
			break
		}
	}
	return nil
}

func (s *Server) PutStream(server proto.Greeter_PutStreamServer) error {

	for  {

		if recv, err := server.Recv(); err != nil {
			fmt.Println(err)
			break
		} else {
			fmt.Println(recv)
		}
	}
	return nil
}

func (s *Server) AllStream(server proto.Greeter_AllStreamServer) error {

	wg := sync.WaitGroup{}

	wg.Add(2)

	go func() {
		defer wg.Done()
		for {
			data, _ := server.Recv()
			fmt.Println("收到客户端消息:" + data.Data)
		}
	}()

	go func() {
		defer wg.Done()
		for {
			_ = server.Send(&proto.StreamResData{Data: "我是服务器"})
			time.Sleep(time.Second)
		}

	}()

	wg.Wait()
	return nil
}

//func (s *Server) AllStream(allStr proto.Greeter_AllStreamServer) error {
//	wg := sync.WaitGroup{}
//	wg.Add(2)
//	go func() {
//		defer wg.Done()
//		for {
//			data, _ := allStr.Recv()
//			fmt.Println("收到客户端消息：" + data.Data)
//		}
//	}()
//
//	go func() {
//		defer wg.Done()
//		for {
//			_ = allStr.Send(&proto.StreamResData{Data: "我是服务器"})
//			time.Sleep(time.Second)
//		}
//	}()
//
//	wg.Wait()
//	return nil
//}

func main() {
	listen, err := net.Listen("tcp", PORT)
	if err != nil {
		panic(err)
	}
	server := grpc.NewServer()
	proto.RegisterGreeterServer(server, &Server{})
	err = server.Serve(listen)
	if err != nil {
		panic(err)
	}
}
